import axios from "axios";
import { getToken, removeToken } from "@/utils/auth.js";
import { Message } from "element-ui";
import Vue from "vue";

function handleMessage(error) {
  const status = error.response?.status;

  switch (status) {
    case 400:
      Message.warning("错误请求：请检查您的请求数据");
      break;
    case 401:
      Message.warning("未授权：请重新登录");
      break;
    case 403:
      Message.warning("禁止访问：您无权访问此资源");
      break;
    case 404:
      Message.warning("找不到资源：请确认URL是否正确");
      break;
    case 409:
      Message.warning("冲突：请求的数据与现有数据冲突");
      break;
    case 500:
      Message.warning({
        message: "服务器内部错误，请稍后重试或联系技术支持。",
        duration: 5000,
      });
      break;
    case 502:
      Message.warning("错误网关：服务器作为网关或代理，但收到了无效的响应");
      break;
    case 503:
      Message.warning("服务不可用：服务器暂时过载或维护");
      // 可以考虑在这里添加重试逻辑
      break;
    case 504:
      Message.warning("网关超时：服务器作为网关或代理，但请求超时");
      break;
    default:
      Message.warning(`服务器错误(${status})：${error.message}`);
      break;
  }
}

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000, 
  withCredentials: false,
});

service.interceptors.request.use(
  (config) => {
    config.headers.authorization = getToken() || '';

    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 0) {
      if (res.code === -221) {
        removeToken();
        const vue = new Vue()
        vue.$loginBox.show();

      } else {

        Message.warning({
          message: res.message || "服务器内部错误",
          duration: 3000,
        });
        return Promise.reject(res || new Error("Error"));
      }
    }
    return res;
  },
  (error) => {
    if (error && error.response) {
      handleMessage(error);
    } else {
      Message.warning("网络请求失败，请检查您的网络连接");
    }

    return Promise.reject(error);
  }
);

export default service;
